<template>
  <div
    class="scroll-wrapper"
    ref='refScroll'
    @scroll="hScroll"
  >
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="article in list"
          :key="article.art_id.toString()"
          :title="article.title"
          @click="hClickIntoArticle(article.art_id.toString())"
        >
          <div slot="label">
            <van-grid
              :column-num="article.cover.images.length"
              v-if="article.cover.images.length"
            >
              <van-grid-item
                v-for="value,idx in article.cover.images"
                :key="idx"
              >
                <van-image
                  lazy-load
                  :src="value"
                />
              </van-grid-item>
            </van-grid>
            <div class="meta">
              <span>{{article.aut_name}}</span>
              <span>{{article.comm_count}}评论</span>
              <span>{{article.pubdate | relativeTime}}</span>
              <span
                class="close"
                v-if="$store.state.tokenInfo.token"
              >
                <van-icon
                  name="cross"
                  @click="isMoreAction(article)"
                />
              </span>
            </div>
          </div>
        </van-cell>

      </van-list>
    </van-pull-refresh>
    <van-popup
      v-model="isShowMoreAction"
      :style="{width:'60%'}"
    >
      <more-action
        @un-like="hUnLike"
        ref="moreaction"
        @report="hReport"
      ></more-action>
    </van-popup>
  </div>
</template>

<script>
import { getArticles, unlikeArticles, reports } from '@/api/articles.js'
import moreAction from './moreAction.vue'
export default {
  name: 'articles',
  props: ['channel'],
  data () {
    return {
      articleID: '', // 文章ID
      list: [], // 文章数据列表
      timestamp: Date.now(), // 时间戳
      loading: false,
      finished: false,
      isLoading: false,
      isShowMoreAction: false // 弹出层
    }
  },
  components: {
    moreAction
  },
  methods: {
    hClickIntoArticle (articleID) {
      this.$router.push('/articleDetail/' + articleID)
    },
    // 点击关闭时调出弹出层，显示不感兴趣界面，同时将当前文章的id保存至data数据项中
    isMoreAction (article) {
      this.isShowMoreAction = true
      // console.log(article)
      this.articleID = article.art_id.toString()
      // 每次点开弹出层显示在初始页面，通过ref引用更改子组件内部的值
      // 由于首次点开时moreaction还未被创建，所以会报错
      // console.log(this.$refs)
      if (this.$refs.moreaction) {
        this.$refs.moreaction.isReport = false
      }
    },
    async hUnLike () {
      try {
        // 1、点击不感兴趣发送请求
        const res = await unlikeArticles(this.articleID)
        console.log(res)
        // 2、从本地删除文章
        // console.log(this.list)
        this.removeArticle(this.articleID)
        // 3、关闭弹出层
        this.isShowMoreAction = false
        this.$toast.success('操作成功')
      } catch (error) {
        console.log(error)
        this.$toast.fail('操作失败')
      }
    },
    removeArticle (articleID) {
      const idx = this.list.findIndex(article => article.art_id.toString() === articleID)
      // console.log(idx)
      if (idx === -1) return
      this.list.splice(idx, 1)
    },
    // 举报文章
    async hReport (value) {
      try {
        // 1、发请求
        const res = await reports(this.articleID, value)
        // 2、删除文章
        this.removeArticle(this.articleID)
        console.log(res)
        // 3、关闭弹层
        this.isShowMoreAction = false
        this.$toast.success('举报成功')
      } catch (err) {
        console.log(err)
        this.$toast.fail('举报失败')
      }
    },
    async onRefresh () {
      // 下拉刷新时发送请求,确保时间戳永远是最新的
      const res = await getArticles(this.channel, Date.now())
      // console.log(res)
      const arr = res.data.data.results
      // 在数据的开始位置添加
      this.list.unshift(...arr)
      // console.log(this.list)
      // 加载状态结束
      this.isLoading = false
    },
    async onLoad () {
      // 发送请求
      const res = await getArticles(this.channel, this.timestamp)
      // console.log(res)
      // 更改下次请求时间戳
      this.timestamp = res.data.data.pre_timestamp
      const arr = res.data.data.results
      // 在结尾处添加取回的数据，通过...展开数据进行添加
      this.list.push(...arr)
      // console.log(this.list)
      // 加载状态结束
      this.loading = false
      // 数据全部加载完成
      if (arr.length === 0) {
        this.finished = true
      }
    },
    // 监听滚动事件
    hScroll () {
      this.scrollTop = this.$refs.refScroll.scrollTop // 把当前滚动条距离顶部的高度保存到this中
    }
  },
  // 当前组件失活后被再次激活后触发此事件，钩子函数，这两个有缓存，另外8个没有缓存
  activated () { // deactivated 失活时被触发，配合 keep-alive使用
    this.$refs.refScroll.scrollTop = this.scrollTop
  }

}
</script>

<style scoped lang='less'>
.meta {
  span {
    margin-right: 10px;
  }
  display: flex;
  .close {
    margin-left: auto;
  }
}
</style>
